package com.usian.security.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.security.entity.LoginUser;
import com.usian.security.entity.Menu;
import com.usian.security.entity.User;
import com.usian.security.exception.CustomException;
import com.usian.security.mapper.MenuMapper;
import com.usian.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: UserDetailsServiceImpl
 * Author:   WGG
 * Date:    2022-12-2022/12/21-15:22
 * Version: 1.0
 * Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        System.out.println(123);
        //查询用户认证信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getUserName, userName);
        User user = userMapper.selectOne(wrapper);
        if (user==null){
            throw new CustomException("用户名或者密码错误");
        }
        System.out.println(456);
        //查询用户对应的权限
        List<Menu> list = menuMapper.getPermissionsByUserId(user.getUserId());
        //声明权限集合
        List<String> permission = null;
        if (CollUtil.isNotEmpty(list)){
            //把list集合中的权限perms数据
            permission = list.stream().map(Menu::getPerms).collect(Collectors.toList());
        }
        //封装UserDetails
        LoginUser loginUser = new LoginUser(user, permission);
        return loginUser;
    }
}
